<!--主题/回复 发布时间戳-->
<script setup>
import {formatDate} from "@ginstone/common-utils/dist/src/utils/DateUtils";
import {onUnmounted, ref, toRefs, watch} from "vue";

const props = defineProps({date: Date})

const date = toRefs(props).date;

// 计算时间插值水平
const calculate = (date) => {
  // 当前时间
  const now = new Date().getTime() / 1000
  // 时间戳
  const time = date.getTime() / 1000

  const seconds = now - time;
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes * 10 / 60) / 10
  const days = Math.floor(hours * 10 / 24) / 10
  // 一分钟内
  if (seconds < 60) {
    return {text: "刚刚", level: 0}
  }
  // 一小时内
  if (minutes < 60) {
    return {text: minutes + "分钟前", level: 1}
  }
  // 一天内
  if (hours < 24) {
    return {text: hours + "小时前", level: 2}
  }
  if (days < 14) {
    return {text: days + "天前", level: 3}
  }
  return {text: formatDate(date, 'yy-MM-dd hh:mm'), level: 10}
}
// 计算结果
const result = ref()

const doCalculate = () => {
  if (date.value) {
    result.value = calculate(date.value)
  }
}

doCalculate();

let interval;
// 自动更新
if (!interval) interval = setInterval(() => {
  doCalculate();
}, 60 * 1000)

watch(date, (nv, ov) => {
  if (date.value) {
    result.value = calculate(nv)
  }
})

onUnmounted(() => {
  if (interval) {
    clearInterval(interval)
  }
})
</script>

<template>
  <el-tooltip v-if="result" :disabled="result.level===10" placement="bottom">
    <template #content>{{ formatDate(date) }}</template>
    <span :class="'level'+result.level">{{ result.text }}</span>
  </el-tooltip>
</template>

<style scoped>
.level0 {
  background-color: #98d75e;
}

.level1 {
  background-color: #93dbf5;
}

.level2 {
  background-color: #f5e393;
}

.level3 {
  background-color: #f5ab25;
}

.level10 {
  background-color: #fc86ef;
}

</style>